package a_sorting_basic.b_selection_sort_using_generics.sorting_helper;

import org.junit.Test;
import utils.ArrayGeneric;

import java.util.Random;

public abstract class SortingHelperB {

    public void testSorting(String desc, int numbers) {
        System.out.println(desc + " on " + numbers + " integer numbers");
        ArrayGeneric arr = initSorting(numbers);
        long startTime = System.nanoTime();
        executeSorting(arr);
        long endTime = System.nanoTime();
        assert testSorted(arr);
        double duration = (endTime - startTime) / 1000000000.0;
        System.out.println("duration -> " + duration + "s");

    }

    private boolean testSorted(ArrayGeneric arr) {
           for (int i = 0; i < arr.length() - 1; i++) {
               if (arr.get(i + 1).compareTo(arr.get(i)) < 0) {
                   return false;
               }
           }
           return true;
    }

    @Test
    public void testSortedMethod() {
        ArrayGeneric<Integer> arr = new ArrayGeneric<>(3);
        arr.put(0,3);
        arr.put(1,4);
        arr.put(2,5);
        boolean b = testSorted(arr);
        if (b) {
            System.out.println("well sorted");
        } else {
            System.out.println("not sorted");
        }
    }

    public abstract ArrayGeneric initSorting(int numbers);
    public abstract void executeSorting(ArrayGeneric array);

    // 生成一个近似排序的数组
    public static ArrayGeneric getNearlySortedIntegerArray(int size, int swapTimes) {
        ArrayGeneric<Integer> array = new ArrayGeneric<>(size);
        for (int i = 0; i < size; i++) {
            array.put(i, i);
        }
        Random rand = new Random();
        for (int i = 0; i < swapTimes; i++) {
            int m = rand.nextInt(size);
            int n = rand.nextInt(size);
            array.swap(m, n);
        }
        return array;
    }

    // 随机生成一个整数数组
    public static ArrayGeneric<Integer> getRandomIntegerArray(int size, int min, int max) {
        ArrayGeneric<Integer> array = new ArrayGeneric<>(size);
        Random rand = new Random(System.currentTimeMillis());
        for (int i = 0; i < array.length(); i++) {
            array.put(i, rand.nextInt(max - min + 1) + min);
        }
        return array;
    }
}
